package persistence;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import kokonut.shop.product.Model;
import kokonut.shop.product.TShirtModel;

public class ProductPersistence {

    public Model loadModelByRef(int ref) {
        TShirtModel shirt = null;
        PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + TShirtModel.class.getName() + " where ref == " + ref;
        List<TShirtModel> shirtList = (List<TShirtModel>) pm.newQuery(query).execute();
        if (!shirtList.isEmpty()) {
            shirt = shirtList.get(0);
        }
        return shirt;
    }

    public List<TShirtModel> loadModelList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        String query = "select from " + TShirtModel.class.getName() + " order by ref asc";
        List<TShirtModel> shirtList = (List<TShirtModel>) pm.newQuery(query).execute();
        return shirtList;
    }

    public void deleteProductByRef(int ref) {

        PersistenceManager pm = PMF.get().getPersistenceManager();
        //Se elimina el producto guardado anteriormente
        Query query = pm.newQuery(TShirtModel.class);
        query.setFilter("ref == refParam");
        query.declareParameters("int refParam");
        query.deletePersistentAll(ref);
    }

    public void saveModel(TShirtModel model) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        System.out.println(pm);
        //Se guarda el producto ya editado
        pm.makePersistent(model);
    }

    public void closePM() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        pm.close();
    }
}